package com.example.oj.service;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.oj.common.Result;
import com.example.oj.entity.User;
import com.example.oj.entity.UserData;
import com.example.oj.mapper.UserDataMapper;
import com.example.oj.mapper.UserMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Objects;

@Service
public class UserService extends ServiceImpl<UserMapper, User> {

    @Resource UserMapper userMapper;
    @Resource UserDataMapper userDataMapper;
    public Integer register(User user){
        LambdaQueryWrapper<User> wrapper = Wrappers.<User>lambdaQuery().eq(User::getUsername, user.getUsername());
        User res = userMapper.selectOne(wrapper);
        if(res != null) return -1;
        user.setPassword(SecureUtil.md5(user.getPassword()));
        user.setCreateDate(new Date());
        userMapper.insert(user);
        UserData userData = new UserData();
        userData.setId(user.getId());
        userData.setUsername(user.getUsername());
        userDataMapper.insert(userData);
        return 0;
    }
    public Integer login(User user){
        LambdaQueryWrapper<User> wrapper = Wrappers.<User>lambdaQuery().eq(User::getUsername, user.getUsername());
        User res = userMapper.selectOne(wrapper);
        if(res == null) return -1;
        if(!res.getPassword().equals(SecureUtil.md5(user.getPassword()))) return -1;
        return 0;
    }
}
